import { useState, useCallback, useEffect } from "react";
import type { UploadProps } from 'antd';
import { Input, Upload } from "antd";
import MessageItem from "../../messageType/MessageItem/index";
import TimeItem from "../../messageType/TimeItem/index";
import ImgItem from "../../messageType/ImgItem/index";
import VoiceItem from "../../messageType/VoiceItem/index";
import FileItem from "../../messageType/FileItem/index";
import ChatListItem from "../../messageType/ChatListItem/index";
import RevockItem from "../../messageType/RevockItem/index";
import Emoji from "../../messageType/Emoji/index";
import ImgO from "../../messageType/Img/index";
import File from "../../messageType/File/index";
import { getMessageList, sendMessage, sendPrivateImg, sendPrivateFile } from '../../../../util/message';
import { getUserInfo, getMid } from '../../../../util';
import { connect } from 'react-redux';
import SelectUser from "../../../../components/SelectUser";
import store from "../../../../store";
import "./index.less";

const { TextArea } = Input;

//定义一个属性用于配置redux中state到 组件中的props的映射关系
const mapStateToProps = (state: any) => {
  return {
    ...state.msg
  }
}
//映射到action的方法，修改state的数据
const mapDispatchToProps = (dispatch: any) => {
  return {
    addMsg: ({ key, list }: any) => {
      dispatch({ type: "ADD_MESSAGE", key, list });
    }
  }
}

function ChatContent(props: any) {
  const { content, localMessageList, addMsg } = props;
  const { id, avatar, conversationType } = content;
  const [messages, setMessages]: any = useState([]);
  const [msg, setMsg] = useState("");
  const [isShowZFIcon, setIsShowZFIcon] = useState(false);
  const [checks, setChecks]: any = useState([]);
  const [friends, setFriends] = useState('');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const userInfo = getUserInfo();

  const getMessages = useCallback(
    () => {
      const list = localMessageList[`${userInfo.username_connect}-${getMid(id)}`] || [];
      console.log(1212, list);
      setMessages(list);
    },
    [localMessageList, id],
  );
  // 文本发送
  const handleSend = useCallback(() => {
    sendMessage(msg, id, conversationType).then((message: any) => {
      const list = messages.concat({
        ...message,
        source: "reply",
        avatar: userInfo.avatar,
        message: msg,
      });
      const key = conversationType === 'singleChat' ? `${message.from}-${message.to}` : id;
      console.log('key', key);
      addMsg({ key, list });
      setMessages(list);
      setMsg('');
    })
  }, [messages, msg, avatar, conversationType]);
  // emoji
  const handleSendEmoji = (path: string) => {
    setMsg(path);
  };
  // 图片
  const handleSendImg = useCallback(
    (url: any) => {
      sendPrivateImg(url, id, conversationType).then((message: any) => {
        const list = messages.concat({
          ...message,
          source: "reply",
          avatar: userInfo.avatar,
          message: url,
        });
        const key = conversationType === 'singleChat' ? `${message.from}-${message.to}` : id;
        addMsg({ key, list });
        setMessages(list);
        setMsg('');
      })
    },
    [messages, msg, avatar, conversationType],
  );
  // 文件
  const handleSendFile = useCallback(
    (file: any) => {
      sendPrivateFile(file, id, conversationType).then((info: any) => {
        const item = {
          ...info,
          ...info.message,
          source: "reply",
          avatar: userInfo.avatar,
          fileName: file.name,
          fileSize: (file.size / 1000).toFixed(2)
        };
        const list = messages.concat(item);
        const key = conversationType === 'singleChat' ? `${item.from}-${item.to}` : id;
        addMsg({ key, list });
        setMessages(list);
        setMsg('');
      })
    },
    [messages, msg, avatar, conversationType],
  );

  // 转发
  const handleGetChecks = (users: any) => {
    console.log('users', users);
  }

  const handleChange = (e: { target: { value: any } }) => {
    const { value } = e.target;
    setMsg(value);
  };

  useEffect(() => {
    getMessages();
  }, [id])

  useEffect(() => {
    // 监听state的变化
    const unsubscribe = store.subscribe(() => {
      console.log('监听中..', store.getState())
      getMessages();
    })
    return () => {
      // 取消监听
      unsubscribe();
    }
  }, [])



  return (
    <>
      <div className="message-box">
        {messages.map((item: any, index: number) => {
          switch (item.type) {
            case "txt":
              return <MessageItem key={item.id} data={{ item, index }} />;
            case "time":
              return <TimeItem key={item.id} data={{ item, index }} />;
            case "img":
              return <ImgItem key={item.id} data={{ item, index }} />;
            case "voice":
              return <VoiceItem key={item.id} data={{ item, index }} />;
            case "file":
              return <FileItem key={item.id} data={{ item, index }} />;
            case "chatList":
              return <ChatListItem key={item.id} data={{ item, index }} />;
            case "revock":
              return <RevockItem key={item.id} data={{ item, index }} />;
          }
        })}
      </div>
      <div className="input-box">
        <div className="input-box-top">
          <Emoji handleSendEmoji={handleSendEmoji} />
          <File handleSendFile={handleSendFile} />
          <ImgO handleSendImg={handleSendImg} />
          <img
            className="input-box-top-icon"
            src="/assets/icon/xiaoxi_zhuanfa@2x.png"
            onClick={() => setIsShowZFIcon(true)}
            alt=""
          />
        </div>
        {
          isShowZFIcon
            ? <>
              <img
                src="/assets/icon/zhuanfa.png"
                alt=""
                className="zhuanfa-icon"
                onClick={() => setIsModalOpen(true)}
              />
              <div className="input-box-bottom">
                <div className="input-box-bottom-btn cancel-btn" onClick={() => setIsShowZFIcon(false)}>
                  取消
                </div>
              </div>
            </>
            : <>
              <TextArea
                className="input-box-textArea"
                value={msg}
                onChange={handleChange}
                onPressEnter={handleSend}
                style={{ resize: "none" }}
              />
              <div className="input-box-bottom">
                <div className="input-box-bottom-btn" onClick={handleSend}>
                  发送
                </div>
              </div>
            </>
        }
      </div>
      <SelectUser isShow={isModalOpen} setIsModalOpen={setIsModalOpen} getChecks={handleGetChecks} title={'发送给'} okText={'发送'} />
    </>
  );
}

export default connect(mapStateToProps, mapDispatchToProps)(ChatContent);
